<?php

namespace Addons\shop\Controller;
use Addons\Shop\Controller\BaseController;
use Addons\Upay\Controller\QRController;
/*
 * 商铺功能  首页
 * 
 */
class IndexController extends BaseController{
    private $error_msg ='';
    function _initialize() {
	parent::_initialize();
        //计算购物车商品数量
        $shopcart_count = D('Addons://Shop/Cart')->getCount();
        $this->assign('shopcart_count',$shopcart_count);
        //获取当前选择的方法 以高亮底部导航
        $footer_current = strtolower(_ACTION);
        $this->assign('footer_current',$footer_current);
        //echo $footer_current;exit;
        //获取是否含有订单
        $has_un_pay = D('Addons://Shop/Order')->hasUnPay();
        $this->assign('has_un_pay',$has_un_pay);
        //获取配置信息
        $shop_config = get_addon_config('Shop');
        $this->assign('shop_config',$shop_config);
    }
   
    //显示首页
    public function index(){
        $map['token'] = $this->use_token;
        //显示店长推荐
        $dept_id = session(get_token().'_dept_shop');
        if($dept_id){
            //读取推荐商品
            $reuslt = D('Addons://Uwork/Dept')->getShow($dept_id);
            $map_show['id'] = array('in',$reuslt);
            $product_show = D('Addons://Shop/Products')->cgetList('all','',$map_show,1,10);
            $this->assign('product_show',$product_show['list']);
        }
        
        $page = I('p')?I('p'):1;
        $data = D('Addons://Shop/Products')->cgetList('all','',$map,$page,6);
        $page = $data['page'];
        $this->assign('page',$page);
        $data = $data['list'];
       if(!IS_AJAX){
            //读取顶部幻灯片
            $banner_list = D('Addons://Shop/Banner')->getList($map);
            $this->assign('banner_list',$banner_list);
            // dump($banner_list);exit;
             //读取活动页
            $map1['token'] = $this->use_token;
            $map1['is_show'] = 1;
            $topic_list = D('Addons://Shop/Topics')->getList($map1); 
             $this->assign('topic_list',$topic_list);
             //读取商品数据
            
            $ordertype = I('ordertype');
            //获取商品列表显示
            $this->assign('list',$data);
            $this->display();
       }else{
           //ajax 下拉刷新数据
            foreach($data as &$vo){
                $vo['url'] = U('productinfo',array('id'=>$vo['id']));
                $vo['head_img'] = get_cover_url($vo['head_img']);
            }
            //AJAX刷新数据
            $this->ajaxReturn($data,'json');
       }
    }
    
    
    //显示分类信息
    public function categories(){
        $map['token'] = $this->use_token;

        //dump($list);exit;
        //获取分类数据

        $type = I('type');
        if(!isset($type) || $type==null ||$type == ''){
        	$type = 'level';
        }
        $this ->assign('type',$type);
        if($type == 'level'){
            $list = D('Addons://Shop/Categories')->arrgetList($map);
            $this ->assign('list',$list);
        	$this->display();
        }else{
            $list = D('Addons://Shop/Categories')->cateList($map);
            foreach($list as $key=>$v){
                $current_cateid = $v['child'][0]['cid'];
                break;
            }
           // dump($list);
           /*  $list1 = D('Addons://Shop/Products')->cgetList($current_cateid,'default',$map,1);
            $data = $list1['list'];
            $this->assign('pageinfo',$list1['page']); */
            
            $this ->assign('cateid',$current_cateid);
            $this ->assign('list',$list);
        	$this->display('category_index');
        }
    }
     //分类信息
    public function footer(){
        $map['token'] = $this->use_token;
        $data = D('Addons://Shop/Products')->cgetList(10,$map);
        //dump($data);exit;
        //echo _ACTION;
        //$this->display();
    }
    //搜索列表页
     public function searchlist(){
        $cate_id = 'all'; //获取所有商品
        $page = I('p')?I('p'):1;
        $ordertype = I('ordertype')?I('ordertype'):'default';
        
        
        //获取商品列表显示
        $map['token'] = $this->use_token;
        if(I('search_val')!==''){
            $map['_string'] = "name like '%".I('search_val')."%'";
            $this->assign("search_val",I('search_val'));
        }
        $list = D('Addons://Shop/Products')->cgetList($cate_id,$ordertype,$map,$page);
        $data = $list['list'];
        $this->assign('pageinfo',$list['page']);
        
        if(IS_AJAX){
            //对数据做格式处理
            foreach($data as &$vo){
                $vo['url'] = U('productinfo',array('id'=>$vo['id']));
                $vo['head_img'] = get_cover_url($vo['head_img']);
            }
            //AJAX刷新数据
            $this->ajaxReturn($data,'json');
        }else{
            $this->assign('ordertype',$ordertype);
            $this->assign('list',$data);
            $this->assign('cate_id',$cate_id);
            $this->display();
        }
    }
    //显示商品列表页
    public function productslist(){
        $cate_id = I('cate_id');
        $page = I('p')?I('p'):1;
        $ordertype = I('ordertype')?I('ordertype'):'default';
        
        
        //获取商品列表显示
        $map['token'] = $this->use_token;
        $list = D('Addons://Shop/Products')->cgetList($cate_id,$ordertype,$map,$page);
        $data = $list['list'];
        $this->assign('pageinfo',$list['page']);
        
        if(IS_AJAX){
            //对数据做格式处理
            foreach($data as &$vo){
                $vo['url'] = U('productinfo',array('id'=>$vo['id']));
                $vo['head_img'] = get_cover_url($vo['head_img']);
            }
            //AJAX刷新数据
            $this->ajaxReturn($data,'json');
        }else{
            $this->assign('ordertype',$ordertype);
            $this->assign('list',$data);
            $this->assign('cate_id',$cate_id);
            $this->display();
        }
    }
    //显示商品详情页
    public function productinfo(){
        
        $id = I('id');
        if(empty($id)){
            return false;
        }
        $map['id'] = $id;
        //商品的基本信息
        $info = D('Addons://Shop/Products')->getInfo($map);
        D('Addons://Shop/Products')->viewNumInc($map['id'],1);
        //商品的购买记录最新15条
        $condition['pid'] = $id;
        $buy_history = M('shop_product_buy_history')->where($condition)->order("create_date desc")->limit(15)->select();
        foreach($buy_history as $key => $value){
            $buy_history[$key]['buyer'] = mb_substr($value['buyer'],0,1,'utf-8')."**";
        }

        $condition['pid'] = $map['id'];
        $total_comment = M('shop_product_comment')->where($condition)->count();
        $condition['p_grade'] = array('gt',3);
        $total_g_comment = M('shop_product_comment')->where($condition)->count();
        $g_rate = round($total_g_comment/$total_comment*100);

        $this->assign('total_comment',$total_comment);
        $this->assign('g_rate',$g_rate);

        $this->assign('buy_history',$buy_history);
        $this->assign('info',$info);
        $this->assign('un_share',true);//为了避免触发文章的奖励信息，此处先紧急处理。回头统一优化
        $this->share($info);
        
        $this->display();
    }
    //显示购物车
    public function cart(){
        //获取数据
        $list = D('Addons://Shop/Cart')->cgetList();
        if(empty($list)){
            //$this->display(emptycart);
            redirect(U('emptycart'));
        }else{
            $this->assign('list',$list);
            $this->display(); 
        }
        
    }
    //显示空购物车
    public function emptycart(){
        $this->display();
    }
    
   //活动页
    public function topic(){
        $id = I('id');
        if(!$id) return false;
        $map['id'] = $id;
        //获取想关id
        $allinfo = D('Addons://Shop/Topics')->getAllInfo($map);
        
        $this->assign('info',$allinfo);
        $this->display();
    }
   //订单页
    public function order(){
        
    }
    
    /*
     * 确认订单功能集
     */
    
    //我的订单
    public function myorder(){
        echo '尚未创建';exit;
        $this->display();
    }
    
    //确认订单
    public function sureorder(){
        $from = I('from')?I('from'):"default";
        //如果是来自购物车的订单，生成订单后，需要删除购物车的相关内容
        $this->assign('from',$from);
            
        //判断是否会员信息
        $token = get_token();
        $openid = get_openid();
        if($openid== -1&&(empty($GLOBALS['user'])||$GLOBALS['user']['status']===0)){
            $this->error("您需要先关注或绑定会员信息");
        }else{
            //获取收货地址信息
            $map1['token'] = $token;
            $map1['openid'] = $openid;
            $address_list = D('Addons://Shop/Address')->getList($map1);
           
            $this->assign('address_list',$address_list);
            //获取允许的支付信息（待定）
            //dump($address_list);exit;
            //获取商品信息
            $id = I('id');
            if(!$id){
                $this->error('没有对应的商品');
            }
            $id = explode(',', trim($id,','));
            
            $products_list = array();
            $p_price = 0;//商品价格
            $r_p_price = 0;//可打折商品的价格
            foreach($id as $vo){
                $vo = explode('-', $vo);
                $map2['id'] = $vo[0];
                $result = D('Addons://Shop/Products')->getInfo($map2);
                if(!$result) continue;
                $result['num'] = $vo[1];
                
                $p_price += $result['true_price'] * $vo[1];
                //可打折商品
                if($result['is_rate']!=0){
                    $r_p_price += $result['true_price'] * $vo[1];
                }
                $products_list[] = $result;
            }
            
            //计算费用
            $price['p_price'] = number_format($p_price,2,".","");//商品金额
            $price['r_price'] = $this->getrprice($r_p_price);
            //减去折扣的优惠价
            $r_price = $price['p_price']-$price['r_price'];
            
            $price['y_price'] = number_format($this->getyprice($r_price),2,".","");//运费  待开发
            $price['total_price'] = $r_price + $price['y_price'];
            
            $price['total_price'] = number_format($price['total_price'],2,".","");
            
            
            $this->assign('price',$price);
            $this->assign('products_list',$products_list);
        }
        
        $token = md5(get_token());
        $this->assign('token',$token);
        //判断商品信息
        $this->display();
    }
    public function commentorder(){
    	
    	$id = I('id');//订单id
    	if(!$id) $this->error('参数错误');
	    	
    	$map['id'] = $id;
    	$map['token'] = get_token();
    	$map['openid'] = get_openid();
    	
    	//$map['orderStatus'] = 1;//正常订单
    	$orderinfo = D('Addons://Shop/Order')->getAllInfo($map);
		
    	//判断订单是否已经被评论
    	
    	$this->assign('order',$orderinfo);
    	$this->display();
    }
    public function submitcomment(){

        //$this->error('订单参数错误');
    	$oid = I('oid');
    	//$num = I('num');
    	if(!$oid) $this->error('订单参数错误');
    	
    	$map['order_id'] = $oid;
    	$map['token'] = get_token();
    	$map['openid'] = get_openid();
    	
    	$order_comment = M('shop_order_comment')->where($map)->find();
    	if($order_comment){
    		$this->error('订单已评论');
    	}
        $map['create_date'] = time();
    	//插入订单评论
    	M('shop_order_comment')->add($map);
    	//插入商品评论
    	if(isset($_POST['pids'])){
    		foreach ($_POST['pids'] as $k => $v){
    			$p_ = $v."_p_grade";
    			$s_ = $v."_s_grade";
    			$p_grade = I($p_);
    			$s_grade = I($s_);
    			if(!$s_grade  || !$p_grade ) {
                    M('shop_order_comment')->where($map)->delete();
                    $this->error('商品参数错误');
                }
    			
    			$data['pid'] = $v;
    			$data['oid'] = $map['order_id'];
    			$data['openid'] = $map['openid'];
    			$data['token'] = $map['token'];
    			$data['p_grade'] = $p_grade;
    			$data['s_grade'] = $s_grade;
                $data['create_date'] = $map['create_date'];
    			$data['comment_explain'] = I($v."_remarks");
    			
    			$rs = M('shop_product_comment')->add($data);
                if(!$rs){
                    M('shop_order_comment')->where($map)->delete();
                    $this->error("商品评论错误！");
                }
    		}
    	}else{
            $this->error("商品参数错误！");
        }
        //改变订单评论状态
        $order['id'] = $oid;
        $order['token'] = $map['token'];
        $order['openid'] = $map['openid'];
        $res = M('shop_orders')->where($order)->setField('commentStatus',1);
        if($res){
            $this->success("评论提交成功！",addons_url('Shop://Index/orderlist',array('type'=>'over')));
        }else{
            $this->error("评论提交失败！");
        }

    }
    public function buyercomment(){
        $pid  = I('pid');
        if(!$pid){$this->error('参数错误！');}
        $type = I('type');
        if($type!="good" && $type!="middle" && $type!="bad"){
            $type = "good";
        }
        $map['pid'] = $pid;
        switch($type){
            case 'good':
                $map['p_grade'] = array('gt',3);
                break;
            case 'middle':
                $map['p_grade'] = array('eq',3);
                break;
            case 'bad':
                $map['p_grade'] = array('lt',3);
                break;
            default:
                return false;
                break;
        }
        $list = M('shop_product_comment')->where($map)->select();
        foreach($list as $key => $value){
            $condition['token'] = $value['token'];
            $condition['openid'] = $value['openid'];
            $vip = M('vip_info')->where($condition)->find();
            $list[$key]['openid'] = mb_substr($vip['username'],0,1,'utf-8');
        }

        $condition['pid'] = $map['pid'];
        /*$condition['token'] = ;
        $condition['openid'] = ;*/

        $total_comment = M('shop_product_comment')->where($condition)->count();

        $condition['p_grade'] = array('gt',3);
        $total_g_comment = M('shop_product_comment')->where($condition)->count();
        $condition['p_grade'] = array('eq',3);
        $total_m_comment = M('shop_product_comment')->where($condition)->count();
        $condition['p_grade'] = array('lt',3);
        $total_b_comment = M('shop_product_comment')->where($condition)->count();

        //$this->error($total_g_comment);
        $g_rate = round(($total_g_comment/$total_comment)*100);
        $m_rate = round($total_m_comment/$total_comment*100);
        $b_rate = round($total_b_comment/$total_comment*100);

        $this->assign('total_g_comment',$total_g_comment);
        $this->assign('total_m_comment',$total_m_comment);
        $this->assign('total_b_comment',$total_b_comment);

        $this->assign('g_rate',$g_rate);
        $this->assign('m_rate',$m_rate);
        $this->assign('b_rate',$b_rate);

        $this->assign('list',$list);
        $this->assign('type',$type);
        $this->assign('pid',$pid);
        $this->display();
    }
    //订单列表页
    public function orderlist(){
       
        $type = I('type');
        if($type!='unpay'&&$type!='pay'&&$type!='over'&&$type!='comment'){
            $type = 'unpay';
        }
        //读取订单列表
        switch ($type) {
            case 'unpay':
                //待支付订单  （逻辑是  选择微信支付 却为支付的订单）
                $map['payType'] = 1; //微信支付
                $map['payStatus'] = 1; //未支付
                break;
            case 'pay':
                //原来是已支付订单，现改成，已支付订单或者  未支付的货到付款订单 且未确认收货
                $map['wuliuStatus'] = array('neq',3);
                $map['_string'] = "payType = 3 OR payStatus = 2";
                break;
            case 'over':
                //已确认收货
                $map['commentStatus'] = 1;
                $map['wuliuStatus'] = 3;
                break;
            case 'comment':
                //已确认收货
                $map['commentStatus'] = 0;
                $map['wuliuStatus'] = 3;
                break;
            default:
                return false;
                break;
        }
        $map['orderStatus'] = 1;
        $map['token'] = get_token();
        $map['openid'] = get_openid();
        $list = D('Addons://Shop/Order')->getAllList($map);
        
        if($type == 'unpay' ){
            foreach($list as &$vo_list){
                //验证商品
                foreach($vo_list['detail'] as $vo){
                    $map['id'] = $vo['p_id'];
                    $pinfo = D('Addons://Shop/Products')->getInfo($map);
                    if($pinfo['true_price']!=$vo['true_price']||$pinfo['old_price']!=$vo['old_price']){
                        $vo_list['can_use']=0;//订单失效
                    }
                }
            }
        }
        
        //dump($list);exit;
        $this->assign('list',$list);
        $this->assign('type',$type);
        $this->display();
    }
    
    public function orderdetail(){
        //此页面停用
        //$this->display();
    }
    /*
     * 用户功能集
     */
    //添加收货地址
    public function addaddress(){
        if(IS_AJAX){
            //保存数据
            $data = $_POST;
            $data['token'] = get_token();
            $data['openid'] = get_openid();
            $result = D('Addons://Shop/Address')->addAddress($data);
            $this->ajaxReturn($result,'json');
        }else{
            $this->display();
        }
    }
    //修改地址
    public function editaddress($id){
        //获取收货地址信息
        if(IS_AJAX){
            $data = $_POST;
            $data['token'] = get_token();
            $data['openid'] = get_openid();
            
            $result = D('Addons://Shop/Address')->editAddress($data);
            $this->ajaxReturn($result,'json');
        }else{
             //获取收货地址信息
            $map['id'] = I('id');
            $map['token'] = get_token();
            //$map['openid'] = $openid;
            $address = D('Addons://Shop/Address')->getInfo($map);
            $this->assign('address',$address);
            $this->display();
        }
        
    }
    //删除地址
    public function deladdress(){
        if(IS_AJAX){
            $id = I('id');
            $result = D('Addons://Shop/Address')->delAddress($id);
            $this->ajaxReturn($result,'json');
        }
    }
    //地址管理
    public function address(){
        //获取收货地址信息
        $map['token'] = get_token();
        $map['openid'] = get_openid();
        $address_list = D('Addons://Shop/Address')->getList($map);
        $this->assign('address_list',$address_list);
        
        $this->display();
    }
    
    //生成订单 (仅支持前端ajax）
    public function neworder(){
        if(IS_AJAX){
            $map1['id'] = I('address_id');
            $address_data = D('Addons://Shop/Address')->getInfo($map1);
            if(!$address_data){
                $result['status'] = false;
                $result['msg'] = '请填写正确的收货地址';
                $this->ajaxReturn($result,'json');
            }
            
            $pay_type = I('pay_type');
            $remarks = I('remarks');
            $products = I('products');
            //解析参数
            $data = $this->depronum($products);
            //拼装参数
            $orderdata['name'] = $address_data['name'];
            $orderdata['phone'] = $address_data['phone'];
            $orderdata['province'] = $address_data['province'];
            $orderdata['city'] = $address_data['city'];
            $orderdata['area'] = $address_data['area'];
            $orderdata['address'] = $address_data['address'];
            $orderdata['remarks'] = $remarks;
            
            $orderdata['p_price'] = $data['p_price'];
            $r_jian = $this->getrprice($data['r_p_price']);
            //减去折扣的优惠价
            $r_price = $orderdata['p_price']-$r_jian;
            
            $orderdata['r_price'] = $r_jian;
            
            $orderdata['y_price'] = $this->getyprice($r_price);//运费待处理
            $orderdata['total_price'] = $r_price + $orderdata['y_price'];
            
            $orderdata['payType'] = $pay_type;//支付方式
            if($pay_type == 4){
                //余额支付
                //判断密码是否正确
                $safecode = I('safecode');
                
                $result_pay =  D('Common/UserCenter')->payGold($this->uid,$orderdata['total_price'],$safecode);
                if($result_pay['status'] == false){
                    $result['status'] = false;
                    $result['msg'] = $result_pay['msg'];
                    $this->ajaxReturn($result_pay,'json');
                }else{
                    $orderdata['payStatus'] = 2;//已支付
                    $orderdata['payTime'] = time();
                }
            }
            $orderdata['detail'] = $data['products_list'];
            $result = D('Addons://Shop/Order')->newOrder($orderdata);
           
            if($result){
                //删除相关的购物车内容 如果是购物车进来的话，生成订单后，则删除想过商品
                $from = I('from');
                foreach($data['products_list'] as $vo){
                	$id[] = $vo['id'];
                
                	//添加商品的购买记录
                	//helingfeng 2015.7.23
                	$buys['buyer'] = $orderdata['name'];
                	$buys['pid'] = $vo['id'];
                	$buys['number'] = $vo['num'];
                	$buys['create_date'] = time();
                	M('shop_product_buy_history')->add($buys);
                	//
                }
                if($from == 'cart'){
                    D('Addons://Shop/Cart')->delCart($id);
                }
                $result['status'] = true;
                $this->ajaxReturn($result,'json');
            }else{
                 $result['status'] = false;
                 $result['msg'] = "订单生成失败";
                $this->ajaxReturn($result,'json');
            }
        }
    }
    //支付页面
    public function payorder(){
        //生成相关订单
        $id = I('id');//订单id
        if(!$id) $this->error('参数错误');
        $map1['id'] = $id;
        //$map['orderStatus'] = 1;//正常订单
        $orderinfo = D('Addons://Shop/Order')->getAllInfo($map1);
        //验证订单
        if(!$orderinfo){
            $this->error('未找到此订单');
        }else if($orderinfo['orderStatus']!=1){
            $this->error('此订单已关闭');
        }else if($orderinfo['payType']!=1){
            $this->error('非在线支付订单');
        }else if($orderinfo['payStatus'] > 1){
            $this->error('此订单已支付过');
        }
        //验证商品
        foreach($orderinfo['detail'] as $vo){
            $map['id'] = $vo['p_id'];
            $pinfo = D('Addons://Shop/Products')->getInfo($map);
            if($pinfo['true_price']!=$vo['true_price']||$pinfo['old_price']!=$vo['old_price']){
                $this->error('此订单已失效');
            }
        }
        
        
        if($orderinfo['payType'] == 1){
            try{
                $apipay = $this->weipay($orderinfo);
            } catch ( \Think\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->assign('apipay',$apipay);
             //数据分享-JS-SDK版,需要认证后使用
            $signPackage = $this->getjssdk();
            if($signPackage){
                //如果获得返回值,则进行后续动作
                $this->assign('signPackage',$signPackage);
            }else{
                $this->error('未授权的支付请求，您需要认证服务号');
            }
            /*dump($apipay);
            dump($signPackage);*/
        }
        $this->assign('orderinfo',$orderinfo);
        $this->display();
    }
    public function codepay(){
    	//生成相关订单
    	$id = I('id');//订单id
    	if(!$id) $this->error('参数错误');
    	$map1['id'] = $id;
    	//$map['orderStatus'] = 1;//正常订单
    	$orderinfo = D('Addons://Shop/Order')->getAllInfo($map1);
    	//验证订单
    	if(!$orderinfo){
    		$this->error('未找到此订单');
    	}else if($orderinfo['orderStatus']!=1){
    		$this->error('此订单已关闭');
    	}else if($orderinfo['payType']!=3){
    		$this->error('订单不属于二维码支付类型');
    	}else if($orderinfo['payStatus'] > 1){
    		$this->error('此订单已支付过');
    	}
    	
    	if($orderinfo['payType'] == 3){
    		try{
    			$code_url = $this->qrpay($orderinfo);
    		} catch ( \Think\Exception $e) {
    			$this->error($e->getMessage());
    		}
    		$this->assign('code',$code_url);
    		dump($code_url);
    	}
    	
    }
    //支付回调地址 (未生效)
    public function backPay(){
        //$data_['txt'] = "回调".'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]." ".I('key').I('id') ;
    	$param = explode("/",$_SERVER["REQUEST_URI"]);
    	$key = "";
    	$id = "";
    	for ($i=0 ; $i<count($param) ; $i++){
    		if($param[$i] == "id"){
    			$id = $param[$i+1];
    		}else if($param[$i] == "key"){
                $temp = explode(".",$param[$i+1]);
    			$key = $temp[0];
    		}
    	}
    	$data_['txt'] = "回调".'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"].$key.$id;
        M('testlog')->add($data_);
        //$key = I('key');
        if($key != 'hantelepayinterface'){
            return false;
        }
        //echo '222';
        //$id = I('id');
        $map['id'] = $id;
        D('Addons://Shop/Order')->isPay($map);
    }
    //支付验证地址 （支付回调失败的时候使用  注：当前默认情况下失败）
    public function searchPay(){
        $id = I('id');//订单id
        $map['id'] = $id;
        $orderinfo = D('Addons://Shop/Order')->getInfo($map);
        if(!$orderinfo){
            $this->ajaxReturn(false,'json');
        }else{
            //验证是否已支付
            $config = get_addon_config('Upay');
            $pay = new \Com\Weipay($config);
            $result =  $pay->searchPay($orderinfo['ordernum']); //获得jsapi支付的必要参数
            if($result['trade_state'] == 'SUCCESS'){
                //支付成功
                $data['transaction_id'] = $result['transaction_id'];
                $data['payTime'] = strtotime($result['time_end']);
                D('Addons://Shop/Order')->isPay($map,$data);
                $this->ajaxReturn(true,'json');
            }else{
                //支付失败
                $this->ajaxReturn(false,'json');
            }
        }
    }
    //临时的解决方案
    public function userCenter(){
        //echo get_openid();
        $openid = get_openid();
        //会员界面
        $url = addons_url("UserCenter://Index/userCenter",array('openid'=>$openid));
        $html = file_get_contents($url);
        $this->assign('html',$html);
        $this->display();
    }
    
    private function weipay($orderinfo){
        $config = get_addon_config('Upay');
        //组装数据
        $data['body'] = "[{$orderinfo['ordernum']}]";
        $data['out_trade_no'] = $orderinfo['ordernum'];
        //下单接口，金额以分为单位
        $data['total_fee'] = $orderinfo['total_price']*100;
        $data['notify_url'] = addons_url('Shop://Index/backPay',array('id'=>$orderinfo['id'],'key'=>'hantelepayinterface'));//跳转程序
    
        $pay = new \Com\Weipay($config,$data);
        $apipay =  $pay->getParameters(); //获得jsapi支付的必要参数
        return $apipay;
    }
    private function qrpay($orderinfo){
    	//$config = get_addon_config('Upay');
    	//组装数据
    	$data['body'] = "测试扫码支付";
    	$data['out_trade_no'] = $orderinfo['ordernum'];
        $data['product_id'] = $orderinfo['ordernum'];
    	//下单接口，金额以分为单位
    	$data['total_fee'] = $orderinfo['total_price']*100;
    	$data['notify_url'] = "http://www.zyyzm.cn/index.php/addon/Shop/Index/backPay/id/".$orderinfo['id']."/key/hantelepayinterface.html";
    	//addons_url('Shop://Index/backPay',array('id'=>$orderinfo['id'],'key'=>'hantelepayinterface'));//跳转程序
    
    	$code_url = new QRController($data);
    	//$apipay =  $pay->getParameters(); //获得jsapi支付的必要参数
    	return $code_url;
    }
    //使用jssdk前需要使用的
    private function getjssdk(){
        //get_access_token();
        $jssdk = new \Com\jssdk();
        return $jssdk->getSignPackage();
    }
    //解析  商品于 数量 1-10  解析为  id 为1的商品  数量为10
    
    private function depronum($id){
        $id = explode(',', trim($id,','));
        if(!is_array($id)) return false;
        $products_list = array();
        $p_price = 0;//商品价格
        $r_p_price = 0;//可打折商品
        foreach($id as $vo){
           $vo = explode('-', $vo);
           $map2['id'] = $vo[0];
           $result = D('Addons://Shop/Products')->getInfo($map2);
           if(!$result) return false;
           if($vo[1] < 1) return false;
           $result['num'] = $vo[1];
           $p_price += $result['true_price'] * $vo[1];
           //可打折商品
            if($result['is_rate']!=0){
                $r_p_price += $result['true_price'] * $vo[1];
            }
           $products_list[] = $result;
       }
        $data['products_list'] = $products_list;
        $data['p_price'] = $p_price;
        $data['r_p_price'] = $r_p_price;
        return $data;
    }
    //获取运费  输入值 商品总金额
    private function getyprice($p_price = 0){
        //获取配置信息里的基础运费和满免额度，满免则为0，不满免则为基础运费
        $config = getAddonConfig('Shop');
        if(is_numeric($config['y_price'])&&is_numeric($config['my_price'])){
            if($config['my_price'] <= $p_price){
                return 0;
            }else{
                return $config['y_price'];
            }
        }else if(is_numeric($config['y_price'])&& !is_numeric($config['my_price'])){
            return $config['y_price'];
        }else{
            return 0;
        }
    }
    //获取折扣价
    private function getrprice($p_price=0){
        $config = get_addon_config('Shop');
        if($config['use_level']== 1 && $p_price !=0){
            $info = D('Common/UserCenter')->getUserInfo();
            if(is_numeric($info['level']['rate'])&&$info['level']['rate']>0&&$info['level']['rate']<=100){
                $r_price = $p_price * (100-$info['level']['rate'])/100;
                $r_price = number_format($r_price,2,".","");
                return (int)$r_price;
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }
    //分享模块
    private function  share($info){
        //分享数据
        $sharedata['appId']='';//服务号可以填写appId
        $sharedata['imgUrl']=get_cover_url($info['head_img']);
        $sharedata['link']=addons_url('Shop://Index/productinfo',array(id=>$info['id']));
        $sharedata['desc']=$info['desc'];
        $sharedata['title']=$info['name'];
        $this->assign('sharedata',$sharedata);

        //数据分享-JS-SDK版,需要认证后使用
        $jssdk = new \Com\jssdk();
        $signPackage = $jssdk->getSignPackage();
        if($signPackage){
            //如果获得返回值,则进行后续动作
            $this->assign('signPackage',$signPackage);
        }
    }
    public function test(){
        
        $result = D('Common/UserCenter')->payGold(1474,10,111);
        dump($result);
    }
    //二纬条码
    public function ercode(){
        $content = I('content');
        $img = create_qrcode($content);
        echo $img;
    }
    
    //订单二维码
    public function orderCode(){
        $ordernum = I('content');
        //echo $ordernum;
        $map['ordernum'] = $ordernum;
        $orderinfo = D('Addons://Shop/Order')->getAllList($map);
        $orderinfo = $orderinfo[0];
        $this->assign('orderinfo',$orderinfo);
        //dump($orderinfo);
        //获取订单详情
        $this->display();
    }
    
    public function homepage(){
        $condition['openid'] = get_openid();
        $res = json_decode(get_userinfo($condition['openid']),true);
        $data = array('nickname'=>$res['nickname'],'sex'=>$res['sex'],'language'=>$res['language'],'city'=>$res['city'],'province'=>$res['province'],'headimgurl'=>$res['headimgurl'],'subscribe_time'=>$res['subscribe_time']);
        M('follow')->where($condition)->setField($data);

        $map['token'] = get_token();
        $map['openid'] = get_openid();
        //用户微信信息
        $userinfo = M('follow')->where($map)->find();


        $this->assign('userinfo',$userinfo);
    	$this->display();
    }
    
}
